// pages/cart/cart.js
Page({
  data: {
    cart: [],
    address: null
  },
  onLoad: function() {
    this.loadCart();
  },
  onShow: function() {
    this.loadCart();
    this.updateCheckStatus();
  },
  chooseAddress: function() {
    let that = this;
    wx.chooseAddress({
      success: function(res) {
        that.setData({
          address: res
        });
      },
      fail: function(err) {
        console.error('选择地址失败', err);
      }
    });
  },
  loadCart: function() {
    let cart = wx.getStorageSync('cart') || [];
    this.setData({
      cart: cart.map(item => {
        item.checked = false;
        return item;
      })
    });
  },
  decreaseQuantity: function(e) {
    let index = e.currentTarget.dataset.index;
    let cart = this.data.cart;
    if (cart[index].goods_count > 1) {
      cart[index].goods_count--;
      this.setData({
        cart: cart
      });
      wx.setStorageSync('cart', cart);
      this.updateCheckStatus(); 
    } else {

      wx.showModal({
        title: '提示',
        content: '是否从购物车中移除该商品？',
        success: (res) => {
          if (res.confirm) {
            cart.splice(index, 1);
            this.setData({
              cart: cart
            });
            wx.setStorageSync('cart', cart);
          }
        }
      });
    }
  },
  
  increaseQuantity: function(e) {
    let index = e.currentTarget.dataset.index;
    let cart = this.data.cart;
    cart[index].goods_count++;
    this.setData({
      cart: cart
    });
    wx.setStorageSync('cart', cart);
    this.updateCheckStatus();
  },
  onGoodsDetail: function(event) {
    const gid = event.currentTarget.dataset.gid;
    console.log('onGoodsDetail gid:', gid);  
    wx.navigateTo({
      url: `/pages/goodsdetails/goodsdetails?gid=${gid}`
    });
  },
  selectAllChange: function(e) {
    let isAllChecked = e.detail.value.length > 0;
    let cart = this.data.cart.map(item => {
      item.checked = isAllChecked;
      return item;
    });
    this.setData({
      cart: cart,
      isAllChecked: isAllChecked
    });
    wx.setStorageSync('cart', cart);
    this.updateCheckStatus();
  },
  
  checkboxChange: function(e) {
    const index = e.currentTarget.dataset.index;
    let cart = this.data.cart;
    cart[index].checked = !cart[index].checked; 
    this.setData({
      cart: cart
    }, () => {
      this.updateCheckStatus();
    });
  },
  
  updateCheckStatus: function() {
    let cart = this.data.cart;
    let checkedCount = 0;
    let totalPrice = 0;
  
    cart.forEach(item => {
      if (item.checked) {
        checkedCount++;
        totalPrice += item.goods_price * item.goods_count;
      }
    });
  
    this.setData({
      checkedCount: checkedCount,
      totalPrice: totalPrice.toFixed(2)
    });
  },
  toPay: function() {
    let checkedGoods = this.data.cart.filter(item => item.checked);
    let totalPrice = checkedGoods.reduce((total, item) => {
      return total + item.goods_price * item.goods_count;
    }, 0).toFixed(2);

    if (checkedGoods.length === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      });
      return;
    }
    let addressInfo = JSON.stringify(this.data.address);
    let params = {
      goodsList: encodeURIComponent(JSON.stringify(checkedGoods)),
      totalPrice: totalPrice,
      addressInfo: encodeURIComponent(addressInfo)
    };  
    wx.navigateTo({
      url: `/pages/pay/pay?goodsList=${params.goodsList}&totalPrice=${params.totalPrice}&addressInfo=${params.addressInfo}`
    });
  },
});